package com.ldc.common.common;

import android.util.Log;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.ldc.common.R;

import java.util.ArrayList;
import java.util.List;

public abstract class CommonRecyclerView<T> extends RecyclerView.Adapter<CommonRecyclerViewHolder> {
    private static final String TAG = "CommonRecyclerView";
    private final List<T> listData;
    private static final int FLAG_EMPTY = 0x111;
    private static final int FLAG_DATA = 0x112;
    private final @LayoutRes Integer layoutId;

    public CommonRecyclerView(Integer layoutId) {
        this.layoutId = layoutId;
        this.listData = new ArrayList<>();
    }


    public List<T> getData() {
        return listData;
    }


    public int getDataSize() {
        return getData() == null ? 0 : getData().size();
    }


    public void setNewData(List<T> data) {
        Log.e(TAG, "setNewData: ");
        listData.clear();
        if (null != data) {
            listData.addAll(data);
        }
        this.notifyDataSetChanged();
    }

    public void addNewData(List<T> data) {
        Log.e(TAG, "addNewData: ");
        if (data == null || data.isEmpty()) {
            return;
        }
        listData.addAll(data);
        this.notifyDataSetChanged();

    }

    public void addItemData(T data) {
        Log.e(TAG, "addItemData: ");
        if (null == data) {
            return;
        }
        listData.add(data);
        notifyItemChanged(listData.size() - 1, listData);
    }

    @NonNull
    @Override
    public CommonRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Log.e(TAG, "onCreateViewHolder: ");
        if (viewType == FLAG_DATA) {
            return CommonRecyclerViewHolder.get(parent, layoutId);
        } else {
            return CommonRecyclerViewHolder.get(parent, R.layout.layout_common_not_data);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull CommonRecyclerViewHolder holder, int position) {
        Log.e(TAG, "onBindViewHolder: ");
        T data = listData.get(position);
        if (null != data) {
            convert2Data(holder, data, position);
        }
    }

    protected abstract void convert2Data(@NonNull CommonRecyclerViewHolder holder, T data, int position);

    @Override
    public int getItemViewType(int position) {
        Log.e(TAG, "getItemViewType: ");
        return super.getItemViewType(position);
    }

    @Override
    public int getItemCount() {
        return listData.isEmpty() ? 1 : listData.size();
    }
}



